package com.sms.core.adapter.impl.mlrt;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sms.client.exception.SendSmsException;
import com.sms.core.adapter.SendSmsAdapter;
import com.sms.core.request.SendContext;
import com.sms.domain.entity.ChannelConfig;

/**
 * @desc 美联软通的发送适配
 * @author wjw
 * @time 2017年11月16日下午3:30:10
 */
public class MeiLianSendSmsAdapter implements SendSmsAdapter {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private BasicResponseHandler responseHandler = new BasicResponseHandler();
	
	@Override
    public void sendSms(SendContext context) throws SendSmsException {
        CloseableHttpClient client = HttpClients.createDefault();
        ChannelConfig cc = context.getChannelConfig();
        HttpPost httpPost = new HttpPost(cc.getUrl());
        HttpEntity httpEntity = builderEntity(context);
        if (httpEntity != null) {
            httpPost.setEntity(httpEntity);
        }
        
        String content = null;
        try {
            content = client.execute(httpPost, responseHandler);
        } catch (Exception e) {
            throw new SendSmsException("短信发送失败", e);
        }
        
        if (!resultExtract(content)) {
            throw new SendSmsException("短信网关返回意外结果 : " + content);
        }
    }
    
	/**
	 * 转换为请求实体
	 * @param context
	 * @return x
	 */
	protected HttpEntity builderEntity(SendContext context) {
		HttpEntity httpEntity = null;
		Map<String, String> map = builderParameter(context);
		if (map != null && !map.isEmpty()) {
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}

			try {
				httpEntity = new UrlEncodedFormEntity(list, getRequestCharset());
			} catch (UnsupportedEncodingException e) {
				logger.warn("将短信编码为POST数据时异常", e);
				httpEntity = null;
			}
		}

		return httpEntity;
	}
	
	/**
     * 转换为HTTP请求的格式
     * @param context xx
     * @return xx
     */
    protected Map<String, String> builderParameter(SendContext context) {
        ChannelConfig cc = context.getChannelConfig();
        Map<String, String> map = new HashMap<>();
        map.put("username", cc.getAccount());
        map.put("password", cc.getPassword());
        map.put("apikey", cc.getParameter("apikey"));
        map.put("mobile", context.getMobile());
        map.put("content", context.getSendContent());
        return map;
    }
    
    /**
     * 提交请求后，处理请求响应
     * @param content x
     * @return x
     */
    protected boolean resultExtract(String content) {
        return StringUtils.startsWith(content, "success:");
    }
    
    /**
     * 请求的字符集
     * @return xx
     */
    protected String getRequestCharset() {
        return "UTF-8";
    }
	
}
